package com.r2coding.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.r2coding.util.Result;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证失败处理器
 *
 * @author: 98k灬
 * @since: 2022/10/19
 * @email: 98k_style@sina.com
 * @公众号: 爪哇Guy灬
 **/
@Component
public class CustomAuthenticationFailureHandler extends SimpleUrlAuthenticationFailureHandler {
    @Resource
    ObjectMapper objectMapper;

    @Override
    public void onAuthenticationFailure(HttpServletRequest request,
                                        HttpServletResponse response,
                                        AuthenticationException exception) throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        Result error = Result.build(HttpStatus.UNAUTHORIZED.value(), "认证失败");
        String json = objectMapper.writeValueAsString(error);
        response.getWriter().write(json);
    }
}
